package com.papers.system.controller;

import cn.dev33.satoken.annotation.SaCheckPermission;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.papers.common.annotation.Log;
import com.papers.common.annotation.RepeatSubmit;
import com.papers.common.core.controller.BaseController;
import com.papers.common.core.domain.PageQuery;
import com.papers.common.core.domain.R;
import com.papers.common.core.page.TableDataInfo;
import com.papers.common.core.validate.AddGroup;
import com.papers.common.core.validate.EditGroup;
import com.papers.common.enums.BusinessType;
import com.papers.common.excel.ExcelResult;
import com.papers.common.exception.ServiceException;
import com.papers.common.utils.poi.ExcelUtil;
import com.papers.system.domain.bo.TJuanKnowledgeBo;
import com.papers.system.domain.dto.TJuanKnowledgeDragDto;
import com.papers.system.domain.dto.TJuanKnowledgeDto;
import com.papers.system.domain.vo.TJuanKnowledgeOutVo;
import com.papers.system.domain.vo.TJuanKnowledgePutVo;
import com.papers.system.domain.vo.TJuanKnowledgeVo;
import com.papers.system.domain.vo.TJuanLeftTreeVo;
import com.papers.system.service.ITJuanChapterService;
import com.papers.system.service.ITJuanKnowledgeService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.NotNull;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;

/**
 * 知识点
 *
 * @author papers
 * @date 2022-10-08
 */
@Slf4j
@Validated
@RequiredArgsConstructor
@RestController
@RequestMapping("/system/juanKnowledge")
public class TJuanKnowledgeController extends BaseController {

    private final ITJuanKnowledgeService iTJuanKnowledgeService;

    private final ITJuanChapterService itJuanChapterService;

    /**
     * 查询知识点列表
     */
    @SaCheckPermission("system:juanKnowledge:list")
    @GetMapping("/list")
    public TableDataInfo<TJuanKnowledgeVo> list(TJuanKnowledgeDto dto, PageQuery pageQuery) {
        return iTJuanKnowledgeService.queryPageList(dto, pageQuery);
    }

    /**
     * 导入数据
     */
    @Log(title = "测试单表", businessType = BusinessType.IMPORT)
    @SaCheckPermission("system:juanKnowledge:import")
    @PostMapping("/importData")
    public R importData(@RequestPart("file") MultipartFile file, String chapterId,String treeType) {
        if (ObjectUtils.isNull(chapterId)) {
            return R.fail("请选择题库或章节");
        }
        InputStream fis = null;
        try {
            fis = file.getInputStream();
            ExcelResult<TJuanKnowledgeOutVo> result = ExcelUtil.importExcel(fis, TJuanKnowledgeOutVo.class, true);
            List<TJuanKnowledgeOutVo> list = result.getList();
            if (list.size() == 0) {
                return R.fail("请先添加数据");
            }
            return iTJuanKnowledgeService.saveBatch(list, chapterId,treeType);
        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            try {
                fis.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }


    /**
     * 导出知识点列表
     */
    @SaCheckPermission("system:juanKnowledge:export")
    @Log(title = "知识点", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(TJuanKnowledgeBo bo, HttpServletResponse response) {
        if (null == bo.getChapterId()) {
            throw new RuntimeException("请选择题库或章节");
        }
        List<TJuanKnowledgePutVo> list = iTJuanKnowledgeService.OutputList(bo);
        if (CollectionUtils.isEmpty(list)) {
            throw new ServiceException("列表为空！");
        }
        ExcelUtil.exportExcel(list, "专业", TJuanKnowledgePutVo.class, response);
    }

    /**
     * 获取知识点详细信息
     *
     * @param knowledgeId 主键
     */
    @SaCheckPermission("system:juanKnowledge:query")
    @GetMapping("/{knowledgeId}")
    public R<TJuanKnowledgeVo> getInfo(@NotNull(message = "主键不能为空")
                                       @PathVariable String knowledgeId) {
        return R.ok(iTJuanKnowledgeService.queryById(knowledgeId));
    }

    /**
     * 新增知识点
     */
    @SaCheckPermission("system:juanKnowledge:add")
    @Log(title = "知识点", businessType = BusinessType.INSERT)
    @RepeatSubmit()
    @PostMapping()
    public R<Void> add(@Validated(AddGroup.class) @RequestBody TJuanKnowledgeBo bo) {
        //int i = iTJuanKnowledgeService.KnowledgeCodeUnique(bo);
        //if (i == 0) {
        //    return R.fail("新增知识点失败，知识点编码" + bo.getKnowledgeCode() + "已存在");
        //}
        return toAjax(iTJuanKnowledgeService.insertByBo(bo) ? 1 : 0);
    }

    /**
     * 拖拽知识点(暂时用于上下换位)
     *
     * @param dto
     * @return
     */
    @PutMapping("/drag")
    public R<Void> drag(@RequestBody TJuanKnowledgeDragDto dto) {
        return toAjax(iTJuanKnowledgeService.dragSort(dto) ? 1 : 0);
    }

    /**
     * 修改知识点
     */
    @SaCheckPermission("system:juanKnowledge:edit")
    @Log(title = "知识点", businessType = BusinessType.UPDATE)
    @RepeatSubmit()
    @PutMapping()
    public R<Void> edit(@Validated(EditGroup.class) @RequestBody TJuanKnowledgeBo bo) {
        return toAjax(iTJuanKnowledgeService.updateByBo(bo) ? 1 : 0);
    }

    /**
     * 删除知识点
     *
     * @param knowledgeIds 主键串
     */
    @SaCheckPermission("system:juanKnowledge:remove")
    @Log(title = "知识点", businessType = BusinessType.DELETE)
    @DeleteMapping("/{knowledgeIds}")
    public R<Void> remove(@NotEmpty(message = "主键不能为空")
                          @PathVariable String[] knowledgeIds) {
        return iTJuanKnowledgeService.deleteKnowledge(knowledgeIds);
    }

    /**
     * 查询知识点list(用于知识点展示)
     *
     * @return
     */
    @GetMapping("/getKnowledgeList")
    public R<List<TJuanKnowledgeVo>> getKnowledgeList(TJuanKnowledgeBo bo) {
        List<TJuanKnowledgeVo> knowledgeList = iTJuanKnowledgeService.getKnowledgeList(bo);
        return R.ok(knowledgeList);
    }

    /**
     * 查询知识点树(待删)
     *
     * @return
     */
    @GetMapping("/getKnowledgeTree")
    public R<List<TJuanLeftTreeVo>> getKnowledgeTree(TJuanKnowledgeBo bo) {
        List<TJuanLeftTreeVo> knowledgeTree = iTJuanKnowledgeService.getKnowledgeTree(bo);
        return R.ok(knowledgeTree);
    }

    /**
     * 查询左侧树(用于章节树)(弃用)
     *
     * @return
     */
    @GetMapping("/getLeftTree")
    public R<List<TJuanLeftTreeVo>> getLeftTree() {
        List<TJuanLeftTreeVo> leftTree = iTJuanKnowledgeService.getLeftTreeList();
        return R.ok(leftTree);
    }

    /**
     * 2022-12-02 更新，因组织树更换，现在majorId应该当做部门id来使用
     * 根据majorId查询课程(用于章节树)
     *
     * @return
     */
    @GetMapping("/getCourseTree/{majorId}")
    public R<List<TJuanLeftTreeVo>> getCourseTree(@PathVariable String majorId) {
        List<TJuanLeftTreeVo> leftTree = iTJuanKnowledgeService.getCourseTreeList(majorId);
        return R.ok(leftTree);
    }

}
